<script setup lang="ts">
import axios from 'axios';
import type { FormRules } from "element-plus"
import { loginApi } from "../login/apis"
import {LoginRequestData} from "@/pages/login/apis/type.js"
import fileUpload from '@@/assets/images/layouts/fileupload3.png';
import sentButton from '@@/assets/images/layouts/shangchuan3.png';
import yaosuka_title from '@@/assets/images/layouts/yaosuka-title.png';
import aiYaoSuKa1 from '@@/assets/images/layouts/ai-word1.png';
import Header from "@@/components/Head/index.vue"
import Footer from "@@/components/footer/index.vue"
import aiYaoSuKa11 from '@@/assets/images/layouts/ai-word11.png';
import aiYaoSuKa2 from '@@/assets/images/layouts/ai-word2.png';
import aiYaoSuKa21 from '@@/assets/images/layouts/ai-word21.png';
import aiYaoSuKa3 from '@@/assets/images/layouts/ai-word3.png';
import aiYaoSuKa31 from '@@/assets/images/layouts/ai-word31.png';
import close from '@@/assets/images/layouts/close.png';
const imageUrl = ref([]) // 提问上传图片，暂时用单张图片。
const imageFileName = ref([]) // 提问上传图片，暂时用单张图片。
import { getCardDetailListApi, getCourseListApi } from "@/api"
import { useUserStore } from "@/pinia/stores/user.js"
import { onBeforeMount, onMounted, ref } from "vue"
import {removeToken} from "@@/utils/cache/cookies";
import goToBottom from "@@/assets/images/layouts/go_to_bottom.png";
import excelFile from "@@/assets/images/layouts/excelfile.png";
import pdfFile from "@@/assets/images/layouts/pdffile.png";
import wordFile from "@@/assets/images/layouts/wordfile.png";
const userStore = useUserStore()
const askTitle = ref("问题显示在这里")
const dialogVisible = ref(false)
const router = useRouter()
const checked = ref(true)
const token = ref("")
const askContent = ref("")
const list = ref([]) // 10条AI推荐列表数据
const username = ref("")
const uploadReferenceFile = ref(null)
const selectedFile = ref(null); // 上传图片/文档，提问
/** 登录按钮 Loading */
const loading = ref(false)
/** 登录表单校验规则 */
const loginFormRules: FormRules = {
  account: [
    { required: true, message: "请输入用户名/账号", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" }
  ],
  code: [
  ]
}
/** 登录表单元素的引用 */
const loginFormRef = useTemplateRef("loginFormRef")
/** 登录表单数据 */
const loginFormData: LoginRequestData = reactive({
  username: "",
  account: "",
  password: "",
  mobile: "",
  code: ""
})
onBeforeMount(() => {
  // 组件已完成响应式状态设置，但未创建DOM节点
  username.value = userStore.getUserName().value
  token.value = userStore.token
  if (token.value === '') {
    dialogVisible.value = true
  }
  getCardDetailList()
  document.addEventListener('keydown', function(event) {
    if (event.key === "Enter" && event.shiftKey) {
      console.log("Shift + Enter pressed");
      event.preventDefault(); // 阻止默认行为，例如表单提交
      // 在当前光标位置插入一个换行符
      // const start = this.selectionStart;
      // const end = this.selectionEnd;
      askContent.value = askContent.value + "\n";
      // 重新设置光标位置
      // this.selectionStart = this.selectionEnd = start + 1;
    }

    if (event.key === "Enter" && !event.shiftKey) {
      console.log(" Enter pressed");
      event.preventDefault(); // 阻止默认行为，例如表单提交
      // askQuestion()
    }
  });
})
/** 登录 */
function handleLogin() {
  loginFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    loginFormData.username = loginFormData.account
    loginFormData.mobile = loginFormData.account
    loading.value = true
    loginApi(loginFormData).then(({ data }) => {
      userStore.setUsername(data.mobile) // token-admin
      userStore.setToken(data.token) // token-admin
      userStore.setUserId(data.id) // token-admin
      dialogVisible.value = false
    }).catch(() => {
      ElMessage.error({
        message: "验证失败",
        type: "warning",
        duration: 2000
      })
      // loginFormData.password = ""
    }).finally(() => {
      loading.value = false
    })
  })
}
function logout() {
  token.value = ""
  username.value = ""
  removeToken()
  userStore.setToken("") // token-admin
  userStore.setUsername("")
}
function goStudyUrl(id) {
  router.push({
    name: 'studySecond',
    params: {
      id: id
    }
  })
}
function resetForm () {
  // refs["formLogin"].resetFields()
}
function goToUrl (type) {
  router.push({
    path: type
  })
}
function getCardDetailList() {
  const data2 = { page: 1, type: "1", limit: 10 }
  getCourseListApi(data2).then(({ data: tableData }) => {
    // console.log(tableData)
    // list.value = tableData
    for (let i = 0; i < tableData.length; i++) {
      list.value.push({
        id: tableData[i].id,
        title: tableData[i].title,
        description: tableData[i].description,
        create_time: tableData[i].create_time,
        source_author: tableData[i].source_author,
        content: tableData[i].content
      })
    }
    console.log(list)
  }).catch((data) => {
    console.log(data)
  }).finally(() => {
    loading.value = false
  })
}
function askQuestion() {

  askTitle.value = askContent.value
  console.log('askQuestion')
}
function triggerFileInput() {
  uploadReferenceFile.value.click();
}

function handleFileUpload(event) {
  const files = event.target.files[0];
  let isExcelFile = 0;
  let isPdfFile = 0;
  let isWordFile = 0;
  console.log(files)
  // 允许上传的文件类型,word,excel, pdf, ppt, pptx, jpg, png
  if (files.type == 'image/jpeg' || files.type == 'image/png' || files.type == 'image/jpg' ||
    files.type == 'application/pdf' || files.type == 'application/msword'  ||
    files.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||  files.type == 'application/vnd.ms-excel'
    || files.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || files.type == 'application/vnd.ms-powerpoint'
    || files.type == 'application/vnd.openxmlformats-officedocument.presentationml.presentation' || files.type == 'application/vnd.ms-powerpoint.presentation.macroEnabled.12' ) {
    if (files && files.type) {
      if (files.type == 'application/vnd.ms-excel' || files.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        isExcelFile = 1;
      }
      if (files.type == 'application/pdf') {
        isPdfFile = 1;
      }
      if (files.type == 'application/msword' ||  files.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
        isWordFile = 1;
      }
      selectedFile.value = files; // 存储选中的文件，可以在这里做进一步处理，如上传等。
      // console.log(selectedFile.value); // 或者使用FormData发送文件等操作
      const formData = new FormData();
      formData.append('imgFile', selectedFile.value);
      try {
        axios.post('https://www.sacasaca.com/shop122/uploadfile', formData, {
          headers: { 'Content-Type': 'multipart/form-data' },
        }).then(response => {
          response.data
          console.log(response.data.data.url)
          if (isExcelFile == 1) {
            imageUrl.value.push(excelFile) ;
          } else if (isPdfFile == 1) {
            imageUrl.value.push(pdfFile) ;
          } else if (isWordFile == 1) {
            imageUrl.value.push(wordFile) ;
          } else {
            imageUrl.value.push(response.data.data.url) ;
          }
          imageFileName.value.push(response.data.data.fileName)

        });
      } catch (error) {
        console.error(error);
      }
    } else {
      console.log(files.type)
      ElMessage.error({
        message: "请选择正确的文件类型,允许上传的文件类型,word,excel, pdf, ppt, pptx, jpg, png",
        type: "warning",
        duration: 2000
      })
    }
  }
}

function handleKeyDown(event) {
  if (event.key === 'Enter' && event.shiftKey) {
    // 获取光标位置
    const textarea = event.target;
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const value = textarea.value;
    const textBeforeCursor = value.substring(0, start);
    const textAfterCursor = value.substring(end);
    console.log('Text before cursor:', textBeforeCursor);
    console.log('Text after cursor:', textAfterCursor);
    console.log(value.substring(end).length);
    if (value.substring(end).length == 0) {
      askContent.value = value.substring(0, start) + '\n';
    } else {
      askContent.value = value.substring(0, start) + '\n' + value.substring(end);
    }
  }
}
const changeCloseState = (id, state) => {
  if (state == 0) {
    document.getElementById("close"  + id).style.display = "none";
    document.getElementById("word"  + id).style.display = "none";
  } else {
    document.getElementById("word"  + id).style.display = "block";
    document.getElementById("close"  + id).style.display = "block";
  }
}
const deletePicture = (id) => {
  console.log(id)
  if (id >= 0) {
    imageUrl.value.splice(id, 1);
  }
  console.log(imageUrl.value)
}
</script>

<template>
  <div class="login-container" style="display: flex;flex-direction: column;height: 100vh;">
    <Header :activeId="1" />
    <!-- 登录界面 -->
    <el-dialog v-model="dialogVisible" title="" :width="550" @closed="resetForm">
      <div style="width:80%; margin: 0 auto">
        <div class="title-left">
          <div class="icon icon1" style="height: 10px; width: 60px;" />
          <div class="title">
            请登录
          </div>
        </div>
        <el-form :model="loginFormData" ref="loginFormRef" label-position="left" :rules="loginFormRules" label-width="80px">
          <el-form-item label="用户名" class="username2" prop="account">
            <el-input size="large" autocomplete="off" v-model="loginFormData.account" placeholder="请输入用户名/手机号"  />
            <template #error>
              <div class="custom-error">请输入用户名/手机号</div>
            </template>
          </el-form-item>
          <el-form-item label="密码" class="password2" prop="password">
            <el-input size="large" autocomplete="off" v-model="loginFormData.password" type="password" placeholder="请输入密码" />
            <template #error>
              <div class="custom-error">请输入六位以上的密码</div>
            </template>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div style="display: flex;justify-content: center;">
          <el-button size="large" style="width:100px;" @click="dialogVisible = false">
            取消
          </el-button>
          <el-button size="large" style="width:100px;" type="primary" @click="handleLogin">
            确认
          </el-button>
        </div>
        <div style="display: flex;justify-content: center;">
          <div style="width: 120px; margin-right: 10px;line-height: 40px">
            没有账号？<a href="/#/register" class="register">注册</a>
          </div>
        </div>
      </template>
    </el-dialog>
    <div class="ai w-1200" element-loading-text="Loading...">
      <div class="ai-left">
        <div class="ai-left-tool">
          <div class="ai-left-tool-item selected">
            <div class="icon icon1 " style="height: 31px; width: 31px;"  @click="goToUrl('/ai')"/>
            <div class="title " @click="goToUrl('/ai')">
              推荐
            </div>
          </div>
          <div class="ai-left-tool-item">
            <div class="icon icon2" style="height: 30px; width: 30px;"  @click="goToUrl('/ai2')"/>
            <div class="title" @click="goToUrl('/ai2')">
              问答
            </div>
          </div>
          <div class="ai-left-tool-item">
            <div class="icon icon3 iconSelected" style="height: 32px; width: 30px;"  @click="goToUrl('/ai3')"/>
            <div class="title titleSelected" @click="goToUrl('/ai3')"> 学习 </div>
          </div>
          <div class="ai-left-tool-item">
            <div class="icon icon5" style="height: 30px; width: 30px;" />
            <div class="title"> 专业工具 </div>
          </div>
          <div class="ai-left-tool-item">
            <div class="icon icon6" style="height: 30px; width: 30px;"  @click="goToUrl('/ai4')"/>
            <div class="title" @click="goToUrl('/ai4')"> 记录 </div>
          </div>
          <div class="ai-left-tool-item">
            <div class="icon icon7" style="height: 30px; width: 30px;"  @click="goToUrl('/ai5')"/>
            <div class="title" @click="goToUrl('/ai5')"> 指南 </div>
          </div>
        </div>
      </div>

      <div class="ai-right">
        <div style="width: 892px; height: calc(100% - 64px);overflow-x: hidden; overflow-y: scroll;" class="ai-right-top scroll">
          <div style="width:100%;display: flex; padding: 10px 0; flex-direction: row;  justify-content: flex-end;}">
            <div class="dot-flashing">
              <div class="circle"></div>
              <div class="circle"></div>
            </div>
            <div v-if="askTitle.length > 0" style="padding: 6px 10px;height:32px;border-radius: 8px;line-height:22px;font-size: 14px;color: #333333; background-color: rgba(218,216,216,0.68);">{{askTitle}}</div>
          </div>
          <div class="ysk-box" v-for="item in list" :key="item.id">
            <div class="top">
              <div class="left">
                <div class="text1 active1">
                  政策
                </div>
                <div class="text1">
                  资讯
                </div>
                <div class="text1">
                  文献
                </div>
                <div class="text1">
                  数据
                </div>
                <div class="text1">
                  课件
                </div>
                <div class="text1">
                  其他
                </div>
              </div>
              <div class="right">
                <div class="right-item">
                  <div class="imgKa"><img :src="aiYaoSuKa11" class="img4" /></div>
                  <span class="card-text-red">摘要卡</span>
                </div>
                <div class="right-item">
                  <div class="imgKa"><img :src="aiYaoSuKa2" class="img4" /></div>
                  <span class="text2">应询卡</span>
                </div>
                <div class="right-item">
                  <div class="imgKa"><img :src="aiYaoSuKa3" class="img4" /></div>
                  <span class="text2">要素卡</span>
                </div>
              </div>
            </div>

            <div class="center1" @click="goStudyUrl(item.id)">
              <div class="left">
                <div class="row1">
                  {{item.title}}
                </div>
                <div style="width: 88%;height: 1px;background-color: #dcdbdb;margin: 0 auto;"></div>
                <div class="row2">
                  篇数:10{{item.source_author}} <span style="width:24px;padding: 0 8px;color:#bfbdbd">|</span> 关联度区间：1-10
                </div>
                <div style="padding:16px 16px 16px 16px;">
                  <el-button type="primary" class="btn" style="background-color: #FFAA43;width:244px;height:40px;border: 1px solid #FFAA43;">展开学习</el-button>
                </div>
              </div>
              <div class="right">
                <div class="row1">
                  SACA总括：
                </div>
                <div class="row2">
                  <span class="text5"> {{item.content}}</span><!---->
                </div>
              </div>
            </div>
          </div>
          <div style="height: 30px;width:100%;display: flex;flex-direction: column;">
            <div class="go_to_bottom">
              <el-image :src="goToBottom" style="width:40px;height:40px;" alt="" width="40" height="40"></el-image>
            </div>
          </div>
        </div>
        <div class="askwrap">
          <div class="">
            <!-- <div class="question-content-box"></div> -->
            <div class="question-content-box0"></div>
            <div class="question-content-box2">
              <div class="ysk-box-ask">
                <el-input type="textarea" @keydown="handleKeyDown" :rows="3" resize='none' autocomplete="off" placeholder="请输入问题，可通过shift+回车换行"  v-model="askContent" class="textarea"></el-input>
              </div>
              <div class="imgbox">
                <div style="width:400px;display: flex;flex-direction:row;">
                  <div style="width:800px;height:32px;display: flex;flex-direction: row;" v-if="imageUrl.length > 0">
                    <div v-for="(item,index) in imageUrl" style="width:32px;height:32px;margin-right: 8px;position: relative;">
                      <el-image  @mouseout="changeCloseState(index,0)" @mouseover="changeCloseState(index,1)" :src="item" class="img3 cpt" style="width:32px;height:32px;border-radius: 8px;"></el-image>
                      <div @mouseout="changeCloseState(index,0)"  @mouseover="changeCloseState(index,1)" @click="deletePicture(index)" :ref="'close'+index" :id="'close'+index" :style="{ backgroundImage: 'url(' + close + ')', position: 'absolute',top: '-16px', left: '10px', width : '16px', height: '16px', backgroundSize: 'contain',display: 'none' }" ></div>
                      <div @mouseout="changeCloseState(index,0)"  @mouseover="changeCloseState(index,1)" @click="deletePicture(index)" :id="'word'+index" style="position: absolute; top: 32px; left: -10px; min-width : 60px; height: 24px;overflow: hidden;border-radius: 8px ;line-height:14px;font-size: 12px;display: none;background-color: rgba(221,246,246,0.78);padding: 5px 10px; " >{{imageFileName[index]}}</div>
                    </div>
                  </div>
                </div>
                <div style="width:200px;height: 100%;"></div>
                <div style="width:200px;display: flex;gap: 0 10px;justify-content: flex-end;flex-direction: row;">
                  <button @click="triggerFileInput" style="border: 0;background-image: none;border-radius: 0.375rem;background-color: transparent;cursor: pointer;align-items: center;display: flex;">
                    <el-tooltip class="box-item" effect="dark" content="上传附件，最多只能上传8个附件。">
                      <img :src="fileUpload" class="img3 cpt">
                    </el-tooltip>
                  </button>
                  <input ref="uploadReferenceFile" style="display: none;" type="file" @change="handleFileUpload" />
                  <button @click="askQuestion" style="border: 0;background-image: none;border-radius: 0.375rem;background-color: transparent;cursor: pointer;align-items: center;display: flex;">
                    <el-tooltip class="box-item" effect="dark" content="发送">
                      <img :src="sentButton" class="img2 cpt">
                    </el-tooltip>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div style="width:100%;height: 32px;line-height: 30px;text-align: center;font-size:12px;color:#a1a0a0">本次会话由AI生成，仅供参考。</div>
      </div>
    </div>
  </div>
</template>
<style src="@/pages/ai/style/yaosukaList.css"  scoped></style>
<style lang="scss" scoped>
#app {
  height: 100%;
  overflow-y: hidden;
}
#app::-webkit-scrollbar {
  display: none;
}
</style>
